package cmpe451.group7.dbserver.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmpe451.group7.dbserver.dao.UserDAO;
import cmpe451.group7.dbserver.entity.User;
import cmpe451.group7.dbserver.util.Utils;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public UserServlet() {
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter responseWriter = response.getWriter();
		Map<String, String[]> parameters = request.getParameterMap();
		Set<String> keys = parameters.keySet();
		UserDAO userDAO = new UserDAO();

		if (keys.contains("all")) {
			List<User> users = userDAO.getAllUsers();
			Utils.JSONWriter(users, responseWriter);
		} else if (keys.contains("id")) {
			User u = userDAO.findUser(Long.parseLong(parameters.get("id")[0]));
			Utils.JSONWriter(u, responseWriter);
		} else {
			responseWriter.print("{ result=\"failure\" }");
		}

		responseWriter.close();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

}
